<template>
  <el-text class="mx-1 title-text">
      华北电力大学大学生创新创业计划申请表
    </el-text>
    <el-form :model="form" label-width="120px" :rules="rules">
        <el-form-item label="项目名字" prop="form" :rules="rules.name">
            <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="项目类别" prop="empty">
            <el-radio-group v-model="form.category" class="ml-4">
              <el-radio label="0" size="large">创新训练项目</el-radio>
              <el-radio label="1" size="large">创业训练项目</el-radio>
              <el-radio label="2" size="large">创业实践项目</el-radio>
            </el-radio-group>
        </el-form-item>
        
                <el-form-item label="负责人及成员" >
                    <el-button type="primary" round @click="addMember()">添加成员</el-button>
                </el-form-item>
                <el-form-item label="负责人" class="indented-form-item" v-model="members[0]" >
                    <div class="input-row">
                    <el-input v-model="members[0].userId" placeholder="成员学号"  @blur="members[0].userId?getStudent(members[0].userId,0):''" clearable />
                    <el-input v-model="members[0].name" placeholder="姓名"  disabled />
                    </div>
                    <div class="input-row">
                    <el-input v-model="members[0].department" placeholder="院系"  disabled />
                    <el-input v-model="members[0].major" placeholder="专业"  disabled />
                    </div>
                    <div class="input-row">
                    <el-input v-model="members[0].phone" placeholder="电话"  disabled />
                    <el-input v-model="members[0].work" placeholder="分工"   clearable />
                    </div>
                </el-form-item>

                <el-form-item v-for="(member, index) in members.slice(1)" :key="member.id" label="成员" class="indented-form-item" >
                    <div class="input-row">
                    <el-input v-model="member.userId" placeholder="成员学号"  @blur="member.userId?getStudent(member.userId,index+1):''" clearable />
                    <el-input v-model="member.name" placeholder="姓名"  disabled />
                    </div>
                    <div class="input-row">
                    <el-input v-model="member.department" placeholder="院系"  disabled />
                    <el-input v-model="member.major" placeholder="专业"  disabled />
                    </div>
                    <div class="input-row">
                    <el-input v-model="member.phone" placeholder="电话"  disabled />
                    <el-input v-model="member.work" placeholder="分工"  clearable />
                    <el-button class="input-row" v-if="members.length > 2" type="danger" @click="removeMember(index+1)">删除</el-button>
                    </div>
                   
                  </el-form-item>

                
        
        <el-form-item label="指导老师"  v-model="teacher" >
                    <div class="input-row">
                    <el-input v-model="teacher.userId" placeholder="成员学号"  @blur="getTeacher(teacher.userId)" clearable />
                    <el-input v-model="teacher.name" placeholder="姓名"  disabled />
                    </div>
                    <div class="input-row">
                    <el-input v-model="teacher.department" placeholder="院系"  disabled />
                    <el-input v-model="teacher.major" placeholder="专业" disabled />
                    </div>
                    <div class="input-row">
                    <el-input v-model="teacher.phone" placeholder="电话"  disabled />
                    <el-input v-model="teacher.position" placeholder="职位"   clearable />
                    </div>
                </el-form-item>
        <el-form-item label="企业老师"  v-model="proEteacher" prop="empty">
                    <div class="input-row">
                    <el-input v-model="proEteacher.name" placeholder="姓名" clearable />
                    </div>
                    <div class="input-row">
                    <el-input v-model="proEteacher.department" placeholder="院系" clearable />
                    <el-input v-model="proEteacher.major" placeholder="专业" clearable />
                    </div>
                    <div class="input-row">
                    <el-input v-model="proEteacher.phone" placeholder="电话" clearable />
                    <el-input v-model="proEteacher.position" placeholder="职位" clearable />
                    </div>
         </el-form-item>
        <el-form-item label="项目简述" prop="empty">
            <el-input v-model="form.brieflno" type="textarea" placeholder="简述项目内容，控制在200字以内"/>
        </el-form-item>
        <el-form-item label="上传附件">
            <el-upload
                    v-model:file-list="fileList"
                    class="upload-demo"
                    multiple
                    :on-change="handleFileChange"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :before-remove="beforeRemove"
                    :limit="3"
                    :on-exceed="handleExceed"
                    :headers="uploadHeaders"
                    :auto-upload="false"
                  >
                    <el-button type="primary" >上传附件</el-button>
                </el-upload>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSubmit">创建</el-button>
            <el-button @click="cancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>
  
<script setup>
import { ref, computed ,watchEffect,toRaw } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTokenStore } from '@/stores/token.js'
const router = useRouter();
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from '@element-plus/icons-vue'


// do not use same name with ref
const form = ref({
    name: '',
    category:'',
    brieflno:'',

})

//负责人和成员
const members=ref([
    {   name:'',
        department: "",
        major: "",
        phone: "",
        userId: "",
        work:''
        
    },
    {   name:'',
        department: "",
        major: "",
        phone: "",
        userId: "",
        work:''
        
    }

])
//老师
const teacher=ref(
    {   name:'',
        department: "",
        major: "",
        phone: "",
        userId: "",
        position:''
        
    }

)

//企业老师
const proEteacher=ref({
        name:'',
        department: "",
        major: "",
        phone: "",
        position: ""
})
//文件
const fileList = ref([])

const handleRemove = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  )
}

const beforeRemove = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}

//向成员数组中加新成员
const addMember=()=>{
    if(members.value.length<5){
    members.value.push({   name:'',
        department: "",
        major: "",
        phone: "",
        userId: ""
        
    })
 }
}

//删除成员
const removeMember=()=>{
    if(members.value.length>2){
        members.value.pop();
    }
   
}
//获取单个成员

import {getStudentService,getTeacherService,uploadService,applicationService} from '@/api/Item.js'
import { useRouter } from 'vue-router'
const getStudent=async(userId,index)=>{
    let result=await getStudentService(userId)
    members.value[index]=result.data
    console.log(members.value[0])
}
//获取单个老师
const getTeacher=async(userId)=>{
    let result=await getTeacherService(userId)
    teacher.value=result.data
}

//用于表单校验模型、表单非空
const rules = ref({
  empty: [
        { required: true, message: '输入不能为空', trigger: 'blur' }
    ]
   
})

//上传附件
const fileIndex=ref(0)
const handleFileChange=async(file)=>{
   let  type=0
   let result=await uploadService(file,type)
   console.log(result.data)
  fileList.value=result.data
}

 //preEteacher 判空
 const isFormValid = computed(() => {
  const values = Object.values(proEteacher.value);
  const allEmpty = values.every(v => v === '');
  const allFilled = values.every(v => v !== '');
  return allEmpty || allFilled;
});
//提交事件
//提交成功清空
const clearData=()=>{
    form.value={
      name: '',
    category:'',
    brieflno:'',
    }
    members.value=[
    {   name:'',
        department: "",
        major: "",
        phone: "",
        userId: "",
        work:''
        
    },
    {   name:'',
        department: "",
        major: "",
        phone: "",
        userId: "",
        work:''
        
    }

]
//老师
 teacher.value=
    {   name:'',
        department: "",
        major: "",
        phone: "",
        userId: "",
        position:''
        
    }

//企业老师
 proEteacher.value={
        name:'',
        department: "",
        major: "",
        phone: "",
        position: ""
}
//文件
const fileList = ref([])
}
const onSubmit = async() => {
  console.log(fileList.value)
  const stuIds=ref([])
    stuIds.value = members.value.map(member => ({ userId: member.userId }));
    const works=ref()
      works.value = members.value.map(member => member.work);
    let params={
      name:form.value.name,
      category:form.value.category,
      tutorId:teacher.value.userId,
      brieflno:form.value.brieflno,
      stuIds:stuIds.value,
      works:works.value,
      proEteacher:proEteacher.value,
      accessories:fileList.value
         
    }
    
   let result=await applicationService(params)
   if(result.code===200){
    ElMessage.success("申报成功")
    clearData();
    router.push('/project/establishment');

   }

    console.log('submit!')
}
//取消事件
const cancel=()=>{
  ElMessage.warning("取消申请")
  clearData();
  router.push('/project/establishment')
}
</script>

<style scoped>
/* 缩进样式表中 */
.indented-form-item {
    padding-left: 40px; /* 例如，增加左内边距 */
    /* 或者 */
    margin-left: 20px; /* 或者增加左外边距 */
}
/* 输入框 */
.input-row {
  display: flex;
  grid-template-columns: repeat(2, 1fr); /* 创建两列 */
  margin-bottom: 10px; /* 调整这个值来改变上下间距 */
  
}

.input-row .el-input {
  flex: 1;
  margin: 0 5px;
}
/* 标题样式 */
.title-text {
  display: block;
  text-align: center;
  font-size: 24px;
  font-weight: bold;
}

</style>
  